package com.mei.allpowerfuladapter.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by Administrator on 2015/9/23.
 */
public class ViewHolder {

    private SparseArray<View> mView;
    private int mPosition;
    private View mConvertView;

    private ViewHolder(Context context,ViewGroup parent,int layoutId,int position){
        Log.i("MainActivity","ViewHolder构造");
        this.mPosition=position;
        this.mView=new SparseArray<>();
        mConvertView= LayoutInflater.from(context).inflate(layoutId,parent,false);
        mConvertView.setTag(this);
    }

    public static ViewHolder get(Context context,View convertView,ViewGroup parent,int layoutId,int position){
        if (convertView==null){
            return new ViewHolder(context,parent,layoutId,position);
        }else {
            ViewHolder holder= (ViewHolder) convertView.getTag();
            holder.mPosition=position;
            return holder;
        }
    }

    /**
     * 通过viewId获取控件
     * @param viewId
     * @param <T>
     * @return
     */
    public <T extends View> T getView(int viewId){
        View view=mView.get(viewId);
        if (view==null){
            view=mConvertView.findViewById(viewId);
            mView.put(viewId,view);
        }
        return (T) view;
    }

    public View getConvertView() {
        return mConvertView;
    }

    public int getPosition() {
        return mPosition;
    }

    /**
     * 设置TextView的值
     * @param viewId
     * @param text
     * @return
     */
    public ViewHolder setText(int viewId,String text){
        TextView tv=getView(viewId);
        tv.setText(text);
        return this;
    }
    /**
     * 设置ImageView的图片
     * @param viewId
     * @param resId
     * @return
     */
    public ViewHolder setImageResource(int viewId,int resId){
        ImageView imageView=getView(viewId);
        imageView.setImageResource(resId);
        return this;
    }
    /**
     * 设置ImageView的图片
     * @param viewId
     * @param bitmap
     * @return
     */
    public ViewHolder setImageBitmap(int viewId,Bitmap bitmap){
        ImageView imageView=getView(viewId);
        imageView.setImageBitmap(bitmap);
        return this;
    }
    /**
     * 设置ImageView的图片
     * @param viewId
     * @param url
     * @return
     */
    public ViewHolder setImageUrl(int viewId,String url){
        ImageView imageView=getView(viewId);
//        ImageLoader.getInstance().display(imageView,url);
        return this;
    }
}
